/**
 * Filename: TodayShareActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/6/29 2:57
 */
package com.github.postsanf.yinian.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.utils.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class BrowseShareActivity extends BaseActivity implements View.OnClickListener {
    private Toolbar mToolbar;
    private ImageView btn_share_wx_timeline;
    private ImageView btn_share_wx_friend;
    private ImageView btn_share_qq_timeline;
    private ImageView btn_share_qq;
    private UMShareAPI mShareAPI;
    private String shareStr;
    private ProgressDialog mProgressDialog;
    Handler downloadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 2) {
                mProgressDialog.dismiss();
                if (localbitmap != null) {
                    new ShareAction(BrowseShareActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                            .withMedia(new UMImage(BrowseShareActivity.this, localbitmap))
                            .share();
                }
            } else if (msg.what == 1) {
                mProgressDialog.dismiss();
                new ShareAction(BrowseShareActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                        .withMedia(new UMImage(BrowseShareActivity.this, new File(localPath)))
                        .share();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_today_share2);
        mShareAPI = UMShareAPI.get(this);
        shareStr = getIntent().getStringExtra("pic");
        initView();
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.today_share_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
//        String[] mPermissionList = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS};
//        ActivityCompat.requestPermissions(BrowseShareActivity.this, mPermissionList, 100);
        btn_share_wx_timeline = (ImageView) findViewById(R.id.btn_share_wx_timeline);
        btn_share_wx_friend = (ImageView) findViewById(R.id.btn_share_wx_friend);
        btn_share_qq_timeline = (ImageView) findViewById(R.id.btn_share_qq_timeline);
        btn_share_qq = (ImageView) findViewById(R.id.btn_share_qq);
        btn_share_wx_timeline.setOnClickListener(this);
        btn_share_wx_friend.setOnClickListener(this);
        btn_share_qq_timeline.setOnClickListener(this);
        btn_share_qq.setOnClickListener(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private String ts;
    private String localPath;
    private Bitmap localbitmap;

    private void GetLocalOrNetBitmap(final String url) {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_DATA);
        new Thread() {
            @Override
            public void run() {
                super.run();
                Bitmap bitmap = null;
                InputStream in = null;
                BufferedOutputStream out = null;
                try {
                    in = new BufferedInputStream(new URL(url).openStream(), 1024);
                    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                    out = new BufferedOutputStream(dataStream, 1024);
                    byte[] b = new byte[1024];
                    int read;
                    while ((read = in.read(b)) != -1) {
                        out.write(b, 0, read);
                    }
                    out.flush();
                    byte[] data = dataStream.toByteArray();
                    localbitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    data = null;
                    downloadHandler.sendEmptyMessage(2);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    private void GetLocalOrNetFile(final String url) {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_DATA);
        ts = "yn_" + System.currentTimeMillis() + ".png";
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!(file.mkdir() || file.isDirectory())) {
            file.mkdirs();
        }
        localPath = "";
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    URL url1 = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream is = conn.getInputStream();
                        File yinianfile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
                        if (!(yinianfile.mkdir() || yinianfile.isDirectory())) {
                            yinianfile.mkdirs();
                        }
                        localPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/yinian/YiNian/" + ts;
                        File f = new File(localPath);
                        if (f.exists()) {
                            f.delete();
                        }
                        FileOutputStream fos = new FileOutputStream(f);
                        int len = 0;
                        byte[] buff = new byte[1024];
                        while ((len = is.read(buff)) != -1) {
                            fos.write(buff, 0, len);
                        }
                        is.close();
                        fos.close();
                        downloadHandler.sendEmptyMessage(1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 朋友圈
            case R.id.btn_share_wx_timeline:
//                GetLocalOrNetFile(shareStr);
                new ShareAction(BrowseShareActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                        .withMedia(new UMImage(BrowseShareActivity.this, shareStr))
                        .share();
                Intent statintent = new Intent(ACTIONs.record);
                statintent.putExtra("key", "eventFriendCircle_6");
                statintent.putExtra("value", 1);
                sendBroadcast(statintent);
                break;
            // 微信好友
            case R.id.btn_share_wx_friend:
                new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                        .withMedia(new UMImage(this, shareStr))
                        .share();
                Intent statintentfriend = new Intent(ACTIONs.record);
                statintentfriend.putExtra("key", "eventWechat_6");
                statintentfriend.putExtra("value", 1);
                sendBroadcast(statintentfriend);
                break;
            // qq空间
            case R.id.btn_share_qq_timeline:
                new ShareAction(this).setPlatform(SHARE_MEDIA.QZONE).setCallback(umShareListener)
                        .withMedia(new UMImage(this, shareStr))
                        .share();
                Intent statintentzone = new Intent(ACTIONs.record);
                statintentzone.putExtra("key", "eventQZone_6");
                statintentzone.putExtra("value", 1);
                sendBroadcast(statintentzone);
                break;
            case R.id.btn_share_qq:
                new ShareAction(this).setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener)
                        .withMedia(new UMImage(this, shareStr))
                        .share();
                Intent statintentqq = new Intent(ACTIONs.record);
                statintentqq.putExtra("key", "eventQQ_6");
                statintentqq.putExtra("value", 1);
                sendBroadcast(statintentqq);
                break;
        }
    }


    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(BrowseShareActivity.this, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(BrowseShareActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(BrowseShareActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(BrowseShareActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    // 友盟统计
    public void onResume() {
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        super.onResume();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
